import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { LoggingService } from '@/services/logging.service';
import { appName, group, product } from '@/common/common';

@Injectable()
export class HttpLoggingMiddleware implements NestMiddleware {
    constructor(private readonly loggingService: LoggingService) {}

    use(req: Request, res: Response, next: NextFunction) {
        (req as any).startTime = Date.now();
        const traceId = (req as any).traceId || 'unknown';

        // 监听响应完成
        res.on('finish', () => {
            const duration = Date.now() - (req as any).startTime;
            const statusCode = res.statusCode;
            // 记录请求开始
            this.loggingService.http('%j', {
                product: product,
                group: group,
                app: appName,
                method: req.method,
                url: req.url,
                ip: req.ip,
                duration: duration,
                traceId: traceId,
                statusCode: statusCode,
            });
        });

        next();
    }
}
